<script setup>
import { ref ,onMounted,watch} from 'vue';
import { Star } from '@element-plus/icons-vue';
import request from '@/utils/request.js'
import { useRouter } from 'vue-router';
import { ElMessage } from 'element-plus';
import { useUserStore } from '@/stores/index.js'

const router = useRouter();
const userStore = useUserStore();
// 搜索框绑定值
const searchQuery = ref('');
const tag1=ref('全部')

// 标签数据
const tags = ref(['全部', '计算机类', '英语类', '数学类', '物理类', '通识类']);

// 问题列表
const QuestionList = ref([])
// 热门问题（前端学习相关）
const hotQuestionList = ref([]);

// 发布问题相关
const createQuestionDialogVisible = ref(false);
const questionForm = ref({
  title: '',
  content: '',
  tag: '计算机类'
});

//修改标签
const handleTag=(tag)=>{
  tag1.value=tag
}

//获得问题列表
const getQuestions = async() => {
  const res = await request.get('/getQuestions',
    {
      params: {
        tag:tag1.value
      },
    }
  );
  QuestionList.value = res.data.questions;
};
//获得热门问题
const getHotQuestions = async() => {
  const res = await request.get('/getHotQuestions');
   console.log("热门问题：");
  console.log(res.data);
  hotQuestionList.value = res.data.hotQuestions;

};
const getQuestions1 = async() => {
  const res = await request.get('/getQuestions',
    {
      params: {
        keyword:searchQuery.value
      },
    }
  );
  QuestionList.value = res.data.questions;
  searchQuery.value = ''
};

// 发布问题
const handleCreateQuestion = async () => {
  // 表单验证
  if (!questionForm.value.title.trim()) {
    ElMessage.error('请输入问题标题');
    return;
  }
  if (!questionForm.value.content.trim()) {
    ElMessage.error('请输入问题内容');
    return;
  }

  try {
    // 这里需要根据您的API调整
    const res = await request.post('/createQuestion', {
      title: questionForm.value.title,
      content: questionForm.value.content,
      tags: questionForm.value.tag,
      askerId:userStore.userId
    });

    if (res.status==200) {
      ElMessage.success('问题发布成功');
      createQuestionDialogVisible.value = false;
      // 重置表单
      questionForm.value = {
        title: '',
        content: '',
        tag: '计算机类'
      };
      // 刷新问题列表
      getQuestions();
    } else {
      ElMessage.error(res.data.message || '发布失败');
    }
  } catch (error) {
    console.error('发布问题失败:', error);
    ElMessage.error('发布失败，请稍后重试');
  }
};

// 观察tag1的变化，重新获取问题列表
watch(tag1, (newVal) => {
  getQuestions();
});
onMounted(() => {
  getQuestions();
  getHotQuestions();
});
</script>

<template>
  <el-container class="layout" style="min-height: 100vh;">
    <el-container class="main-container">
      <el-main class="main-content">
        <!-- 搜索区域 -->
        <div class="search-area">
          <el-input
            v-model="searchQuery"
            placeholder="请输入搜索内容"
            style="width: 70%;"
            prefix-icon="el-icon-search"
            class="custom-input"
          />
          <el-button type="success" class="custom-btn" style="margin-left: 8px;" @click="getQuestions1()">搜索</el-button>
          <el-button type="success" class="custom-btn" style="margin-left: 8px;" @click="createQuestionDialogVisible = true">发布问题</el-button>

          <!-- 发布问题对话框 -->
          <el-dialog
            v-model="createQuestionDialogVisible"
            title="发布问题"
            width="600px"
            :close-on-click-modal="false"
          >
            <el-form :model="questionForm" label-width="80px">
              <!-- 问题标题（必填） -->
              <el-form-item label="问题标题" required>
                <el-input
                  v-model="questionForm.title"
                  placeholder="请输入问题标题"
                  maxlength="100"
                  show-word-limit
                />
              </el-form-item>

              <!-- 问题标签 -->
              <el-form-item label="问题标签">
                <el-select v-model="questionForm.tag" placeholder="请选择标签">
                  <el-option
                    v-for="tag in tags.filter(t => t !== '全部')"
                    :key="tag"
                    :label="tag"
                    :value="tag"
                  />
                </el-select>
              </el-form-item>

              <!-- 问题内容（必填） -->
              <el-form-item label="问题内容" required>
                <el-input
                  v-model="questionForm.content"
                  type="textarea"
                  :rows="6"
                  placeholder="请输入问题详细描述"
                  maxlength="1000"
                  show-word-limit
                />
              </el-form-item>
            </el-form>
            <template #footer>
              <span class="dialog-footer">
                <el-button @click="createQuestionDialogVisible = false">取消</el-button>
                <el-button type="primary" @click="handleCreateQuestion">发布</el-button>
              </span>
            </template>
          </el-dialog>
        </div>

        <!-- 标签区域 -->
        <div class="tag-area">
          <el-tag
            v-for="tag in tags"
            :key="tag"
            class="custom-tag"
            @click="handleTag(tag)"
          >
            {{ tag }}
          </el-tag>
        </div>

        <!-- 问题列表 -->
        <!-- 若没有则 -->
        <el-main v-if="QuestionList.length === 0" class="no-questions">暂无问题</el-main>
        <el-card
          v-for="(item, index) in QuestionList"
          :key="index"
          class="question-card"
          shadow="hover"
          v-else
        >
          <div class="card-content">
            <el-avatar :src="item.asker.avatar" size="small" class="avatar" />
            <div class="question-info">
              <h4 class="question-title">{{ item.title }}</h4>
              <p class="question-meta">提问人：{{ item.asker.nickname }}</p>
              <p class="question-meta">提问时间：{{ item.createdAt }}</p>
            </div>
            <el-button type="success" size="small" class="answer-btn" @click="router.push({
              path:'/partner/QuestionDetail',
              query: {
                questionId: item.id
              }
            })">查看回答</el-button>
          </div>
        </el-card>
      </el-main>

      <!-- 热门问题侧边栏 -->
      <el-aside width="320px" class="hot-aside">
        <div class="hot-questions">
          <div class="hot-title">
            热门问题
            <el-icon class="hot-arrow">
              <Star />
            </el-icon>
          </div>
          <ul class="hot-list">
            <li v-for="(item, index) in hotQuestionList" :key="index" class="hot-item"
              @click="router.push({
                path:'/partner/QuestionDetail',
                query: {
                  questionId: item.id
                }
              })"
            >
              <div class="hot-list-number">{{ index + 1 }}</div>
              <span class="hot-list-content" >{{ item.title }}</span>
              <span class="hotness">热度 {{ item.hotScore }}</span>
            </li>
          </ul>
        </div>
      </el-aside>
    </el-container>
  </el-container>
</template>

<style scoped>
.layout {
  padding: 0;
  font-family: 'Microsoft YaHei', sans-serif;
  background-color: #e6f7ef;
}

/* 主容器 */
.main-container {
  position: relative;
  max-width: 1200px;
  margin: 0 auto;
}

/* 主内容区 */
.main-content {
  padding: 24px;
  margin-right: 340px; /* 为固定侧边栏留出空间 */
}

/* 搜索区域 */
.search-area {
  display: flex;
  align-items: center;
  margin-bottom: 24px;
}
.custom-input {
  --el-input-bg-color: #fff;
  --el-input-border-color: #fff;
  --el-input-text-color:black;
  border-radius: 8px;
}
.custom-btn {
  border-radius: 8px;
  transition: all 0.3s;
}

/* 标签区域 */
.tag-area {
  margin-bottom: 24px;
}
.custom-tag {
  --el-tag-bg-color: #34b518;
  --el-tag-border-color: #fff;
  --el-tag-text-color: #e6f7ef;
  --el-tag-hover-bg-color: #fff;
  --el-tag-hover-border-color: #fff;
  border-radius: 16px;
  margin-right: 8px;
  padding: 6px 16px;
  transition: all 0.3s;
  cursor: pointer;
  font-size: 14px;
  height: 32px;
  line-height: 32px;
}
.custom-tag:hover {
  background-color: #fff;
  color: black;
}
/* 问题卡片 */
.no-questions {
  height: 100px;
  display: flex;
  justify-content: center;
  align-items: center;
  font-size: 16px;
  color: #666;
  background-color: #fff;
}
.question-card {
  background-color:white;
  border: none;
  border-radius: 12px;
  margin-bottom: 16px;
  transition: all 0.3s;
}
.card-content {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  padding: 16px;
}
.avatar {
  border: 2px solid #fff;
  border-radius: 50%;
  /* 垂直居中 */
  margin-top: 10px ;
  height: 80px;
  width: 80px;
}
.question-info {
  flex: 1;
  margin-left: 16px;
}
.question-title {
  font-size: 16px;
  font-weight: 600;
  margin-bottom: 8px;
  color: black;
  height: 80%;
}
.question-meta {
  font-size: 14px;
  opacity: 0.8;
  margin-bottom: 4px;
  height: 10%;
}
.answer-btn {
  border-radius: 8px;
  transition: all 0.3s;
}

/* 热门侧边栏 - 固定定位 */
.hot-aside {
  position: fixed;
  top: 80px;
  /* 居中布局时定位到右侧 */
  right: calc(50% - 600px);
  width: auto;
  height: auto;
  max-height: calc(100vh - 40px);
  overflow-y: auto;
  background-color: #e6f7ef;
  border-radius: 12px;
  z-index: 100;
}

.hot-questions {
  padding: 24px;
  background-color:#fff;
  border-radius: 12px;
  box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  cursor: pointer;
}
.hot-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 18px;
  font-weight: 600;
  margin-bottom: 16px;
  color: #1a4e3d;
}
.hot-arrow {
  cursor: pointer;
  transition: transform 0.3s;
  color: red;
}
.hot-list {
  list-style: none;
  padding: 0;
  margin: 0;
}
.hot-item {
  font-size: 14px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
  margin: 10px 0;
  line-height: 1.5;
  height: auto;
  display: flex;
}
.hot-item:hover {
  background-color: #f0f0f0;
}
.hot-item:last-child {
  border-bottom: none;
}
.hotness {
  color: #1a4e3d;
  margin-left: 8px;
  font-size: 13px;
}
.hot-list-number{
  color:red;
  font-size: 18px;
  font-weight: 600;
  margin-right: 8px;
}
.hot-list-content{
  max-width: 230px;
  height: auto;
}
/* 响应式设计 */
@media (max-width: 1200px) {
  .main-container {
    max-width: 100%;
    padding: 0 20px;
  }

  .main-content {
    margin-right: 0;
    width: 100%;
  }

  .hot-aside {
    position: static;
    width: 100%;
    margin-top: 20px;
    max-height: none;
  }
}
</style>
